package net.daum.hibernate;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import net.daum.hibernate.domain.Message;

public class JPAHelloWorld {
	public static void main(String[] args) {
		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("helloworld");
		
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		EntityTransaction entityTransaction = entityManager.getTransaction();
		entityTransaction.begin();
		
		Message message = new Message("Hello World");
		entityManager.persist(message);
		entityTransaction.commit();
		entityManager.close();
		
		entityManager = entityManagerFactory.createEntityManager();
		entityTransaction = entityManager.getTransaction();
		entityTransaction.begin();
		
		List messages = entityManager.createQuery("select m from Message m order by m.text asc").getResultList();
		
		System.out.println(messages.size() + " message(s) found");
		
		for (Object object : messages) {
			Message msg = (Message) object;
			System.out.println(msg.getText());
		}
		
		entityTransaction.commit();
		entityManager.close();
		
		entityManagerFactory.close();
	}
}